package cn.comon.app.scan.service.impl;

import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.comon.app.scan.component.SysConfigBean;
import cn.comon.app.scan.entity.AsReportinfo;
import cn.comon.app.scan.service.AppDownloadProcessService;
import cn.comon.app.scan.service.AsReportinfoService;

/**
 * 根据举报信息提供的APP的URL，下载对应的APP软件
 * @author xujf
 *
 */
@Service
public class CopyOfAppDownloadScheduler {
    @Autowired
    private AsReportinfoService asReportinfoService;
    
    private static Logger logger = Logger.getLogger(CopyOfAppDownloadScheduler.class.getName());
    
    public void startAppDownload(){
        try {
            logger.info("【启动APP下载任务...】");
            ThreadPoolExecutor executor = ThreadPoolService.getTheadPool("downLoadAppThreadPool");
            
            logger.info("APP下载任务线程池中等待队列中的线程数：" + executor.getQueue().size());
            logger.info("APP下载任务线程池中的线程数：" + executor.getPoolSize());
            logger.info("APP下载任务线程池正在执行的线程数：" + executor.getActiveCount());
            if (executor.getQueue().size() < Integer.parseInt(SysConfigBean.getProperty("app.download.size"))) {
                int recordNum = Integer.parseInt(SysConfigBean.getProperty("app.download.size")) - executor.getQueue().size();
                //检索数据表【as_reportinfo】，取得需要下载的appURL
                List<AsReportinfo> appDataList = asReportinfoService.getDownloadApp(recordNum);
                if (appDataList != null && appDataList.size() > 0) {
                    //下载前先将待下载记录下载结果更新为正在下载（downloadResult=-1）
                    asReportinfoService.updateDownloadState2ing(recordNum);
                    for (AsReportinfo asReportinfo:appDataList) {
                    	AppDownloadProcessService appDownloadProcess = new AppDownloadProcessServiceImpl(asReportinfo);
                        executor.execute(appDownloadProcess);
                    }
                }
            } else {
                logger.info("【上次APP下载任务未完成，放弃本次下载任务...】");
            }
            logger.info("【APP下载任务启动完成，正在下载中...】");
        } catch (Exception e) {
            logger.error(e.getMessage());
         }
    }
}